package com.tyk.bookstore.back.auth.manager;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author tyk
 * @description AuthRedisManager
 */
@Component
@RequiredArgsConstructor
public class AuthRedisManager {

    private final StringRedisTemplate stringRedisTemplate;

    private static final String CODE_MSG_PREFIX = "auth:code:msg:";
    private static final int CODE_MSG_EXPIRE_TIME = 5;
    private static final TimeUnit CODE_MSG_EXPIRE_TIME_UNIT = TimeUnit.MINUTES;

    /**
     * 缓存消息验证码
     *
     * @param principal     主体：账号/手机号/邮箱
     * @param certification 消息验证码凭证
     * @param code          消息验证码
     */
    public void cacheLoginCertification(String principal, String certification, String code) {
        stringRedisTemplate.opsForValue().set(
                getLoginCertificationKey(principal, certification),
                code,
                CODE_MSG_EXPIRE_TIME,
                CODE_MSG_EXPIRE_TIME_UNIT
        );
    }

    /**
     * 获取消息验证码
     *
     * @param principal     主体：账号/手机号/邮箱
     * @param certification 消息验证码凭证
     * @return 消息验证码
     */
    public String getLoginCertification(String principal, String certification) {
        return stringRedisTemplate.opsForValue().get(
                getLoginCertificationKey(principal, certification)
        );
    }

    /**
     * 删除消息验证码
     *
     * @param principal     主体：账号/手机号/邮箱
     * @param certification 消息验证码凭证
     */
    public void deleteLoginCertification(String principal, String certification) {
        stringRedisTemplate.delete(
                getLoginCertificationKey(principal, certification)
        );
    }

    /**
     * @param principal     主体
     * @param certification 消息验证码凭证
     * @return key
     */
    private String getLoginCertificationKey(String principal, String certification) {
        return CODE_MSG_PREFIX + principal + ":" + certification;
    }


}
